import json
import os
import uuid
from datetime import datetime
from urllib.parse import unquote

from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.paginator import Paginator
from django.db.models import Q
from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from baseinfo.helpfun import query_to_list, liscense_to_list, liscense_to_list2, member_filter, gettimestr, \
    member_to_excelpath
from isi_api.settings import MEDIA_ROOT, BASE_DIR, API_HOST
from liscense.models import Member, Liscense

# 添加成员
def add_member(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            id_num = data['id_num'].upper()
            mem = Member.objects.filter(id_num=id_num)
            if mem.exists():
                res = {
                    'data': {'member': model_to_dict(mem[0])},
                    'meta': {"status": 801, 'message': "该成员已经存在，请勿重复录入！"}
                }
                return JsonResponse(res)
            member = Member()
            member.name = data['name']
            member.p_num = data['p_num'].upper()
            member.id_num = data['id_num'].upper()
            member.company = data['company']
            member.role = data['role']
            member.save()
            res = {
                'data': {'member': model_to_dict(member)},
                'meta': {"status": 200, 'message': "添加成员成功"}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {"status": 802, 'message': "添加成员失败"}
            }
        return JsonResponse(res)

# 根据查询条件获取成员列表
def get_member(request):
    if request.method == 'GET':
        queryInfo = request.GET
        pagenum = int(queryInfo['pagenum'])
        pagesize = int(queryInfo['pagesize'])
        members = member_filter(queryInfo).order_by('id')
        total = members.count()
        if total:
            paginator = Paginator(members, pagesize)
            num_pages = paginator.num_pages
            if pagenum > num_pages:
                pagenum = 1
            current_page_members = paginator.page(pagenum)

            res = {
                'data': {'page_members': query_to_list(current_page_members), 'total': total, 'pagenum': pagenum},
                'meta': {"status": 200, 'message': '获取成员列表成功'}
            }
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': '未查询到相关数据'}
            }
        return JsonResponse(res)

# 通过id删除member
def remove_member(request, member_id):
    if request.method == "DELETE":
        member = Member.objects.filter(pk=member_id)
        try:
            member[0].delete()
            res = {
                'data': None,
                'meta': {'status': 200, 'message': "成员删除成功！"}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 802, 'message': "成员删除失败！"}
            }
        return JsonResponse(res)

# 通过id获取member信息
def get_member_by_id(request, member_id):
    if request.method == 'GET':
        try:
            member = Member.objects.get(pk=member_id)
            res = {
                'data': {'member': model_to_dict(member)},
                'meta': {'status': 200, 'message': "获取成员信息成功！"}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 802, 'message': "获取成员信息失败！"}
            }
        return JsonResponse(res)

# 编辑成员列表的处理函数
def edit_member(request, member_id):
    try:
        member = Member.objects.filter(pk=member_id)[0]
        data = json.loads(request.body)
        member.name = data['name']
        member.p_num = data['p_num']
        member.id_num = data['id_num']
        member.company = data['company']
        member.role = data['role']
        member.save()
        res = {
            'data': {'member': model_to_dict(member)},
            'meta': {'status': 200, 'message': '用户信息修改成功'}
        }
    except Exception as e:
        res = {
            'data': None,
            'meta': {'status': 802, 'message': '用户信息修改失败'}
        }
    return JsonResponse(res)

# 上传证书文件的视图函数
def upload_liscense(request):
    if request.method == 'POST':
        file = request.FILES.get('liscensefile')
        shortpath = os.path.join('media/liscensetemp', uuid.uuid4().hex + file.name)
        with open(shortpath, 'wb') as temp_file:
            for chunk in file:
                temp_file.write(chunk)
            temp_file.flush()
        fullpath = os.path.join(API_HOST, shortpath)
        res = {
            'data': {'shortpath': shortpath, 'fullpath': fullpath},
            'meta': {'status': 200, 'message': '文件上传成功'}
        }
        return JsonResponse(res)

# 添加证书的视图函数
def add_liscense(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            member = Member.objects.get(pk=data.get('member_id'))
            liscense_name = data.get('name')
            liscense_level = data.get('level')
            liscense_organ = data.get('organ')
            liscense_valid_date = data.get('valid_date')
            start_date = datetime.strptime(liscense_valid_date[0], '%Y-%m-%d').date()
            empire_date = datetime.strptime(liscense_valid_date[1], '%Y-%m-%d').date()
            liscense_path = data.get('filepath')
            liscenses = Liscense.objects.filter(member=member).filter(name=liscense_name).filter(level=liscense_level).filter(organ=liscense_organ)
            if liscenses.exists():
                res = {
                    'data': {'liscense': liscense_to_list(liscenses)},
                    'meta': {'status': 802, 'message': "此证书在系统中已经存在！"}
                }
                return JsonResponse(res)
            # print(liscense_path)
            new_liscense = Liscense()
            new_liscense.member = member
            new_liscense.name = liscense_name
            new_liscense.level = liscense_level
            new_liscense.organ = liscense_organ
            new_liscense.start_date = start_date
            new_liscense.empire_date = empire_date
            if liscense_path:
                liscense_path = os.path.join(BASE_DIR, data.get('filepath'))
                liscense = open(liscense_path, 'rb')
                extension = liscense_path.split('.')[-1]
                folder = os.path.join(BASE_DIR, 'media/liscenses/{0}({1})'.format(member.name, member.id_num))
                if not os.path.exists(folder):
                    os.makedirs(folder)
                filepath = os.path.join(folder, '{0}+{1}{2}+{3}.{4}'.format(member.name, liscense_name, liscense_level,
                                                                            liscense_organ, extension))
                with open(filepath, 'wb') as f:
                    for line in liscense.readlines():
                        f.write(line)
                    f.flush()
                liscense.flush()
                liscense.close()
                os.remove(liscense_path)
                filepath = filepath.split(MEDIA_ROOT + '/')[1]
                new_liscense.pdffile = filepath
            new_liscense.save()
            res = {
                'data': None,
                'meta': {'status': 200, 'message': '创建证书成功'}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 801, 'message': '添加证书失败!'}
            }
        return JsonResponse(res)

# 获取证书列表
def get_liscense(request):
    if request.method == 'GET':
        # liscenses = Liscense.objects.all()
        # liscense_list = liscense_to_list(liscenses)
        queryInfo = request.GET
        pagenum = queryInfo['pagenum']
        pagesize = queryInfo['pagesize']
        members = member_filter(queryInfo)
        total = members.count()
        if total:
            paginator = Paginator(members, pagesize)
            num_pages = paginator.num_pages
            if int(pagenum) > num_pages:
                pagenum = 1
            current_page_members = paginator.page(pagenum)

            member_list = liscense_to_list2(current_page_members)
            res = {
                'data': {'member_list': member_list, 'total': total, 'pagenum': pagenum},
                'meta': {'status': 200, 'message': "获取证书列表成功"}
            }
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': '未查询到相关数据'}
            }
        return JsonResponse(res)


# 改变证书审核状态的视图函数
def change_liscense_state(request, liscense_id, state):
    if request.method == 'PUT':
        try:
            liscense = Liscense.objects.filter(pk=liscense_id)[0]
            token = request.META.get("HTTP_AUTHORIZATION")
            user_id = cache.get(token)
            user = User.objects.filter(pk=user_id)[0]
            if state == 'false':
                liscense.is_confirmed = False
                liscense.confirm_user = None
            elif state == 'true':
                liscense.is_confirmed = True
                liscense.confirm_user = user
            liscense.save()
            liscense = liscense_to_list([liscense])[0]

            res = {
                'data': {'liscense': liscense},
                'meta': {'status': 200, 'message': "修改用户状态成功"}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 801, 'message': "修改用户状态失败"}
            }
        return JsonResponse(res)

# 根据id删除证书信息
def remove_liscense(request, liscense_id):
    if request.method == 'DELETE':
        try:
            liscense = Liscense.objects.get(pk=liscense_id)
            liscense.is_delete = True
            liscense.save()
            res = {
                'data': None,
                'meta': {'status': 200, 'message': "证书删除成功！"}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 802, 'message': "删除失败，证书不存在或服务器内部错误"}
            }
        return JsonResponse(res)

# 根据id编辑证书信息
def edit_liscense(request, liscense_id):
    if request.method == 'GET':
        try:
            liscense = Liscense.objects.get(pk=liscense_id)
            liscense = liscense_to_list([liscense])[0]
            res = {
                'data': {'liscense': liscense},
                'meta': {'status': 200, 'message': '获取liscense信息成功'}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 801, 'message': '获取liscense信息失败'}
            }
    elif request.method == 'PUT':
        data = json.loads(request.body)
        liscense_id = data.get('id')
        liscense = Liscense.objects.get(pk=liscense_id)
        member = liscense.member
        liscense_name = data.get('name')
        liscense_level = data.get('level')
        liscense_organ = data.get('organ')
        liscense_valid_date = data.get('valid_date')
        start_date = datetime.strptime(liscense_valid_date[0], '%Y-%m-%d').date()
        empire_date = datetime.strptime(liscense_valid_date[1], '%Y-%m-%d').date()
        # 先判断修改后的liscense在系统中是否已经存在了
        liscenses = Liscense.objects.filter(member=member).filter(name=liscense_name).filter(
            level=liscense_level).filter(organ=liscense_organ).exclude(pk=liscense_id)
        if liscenses.exists():
            res = {
                'data': {'liscense': liscense_to_list(liscenses)},
                'meta': {'status': 802, 'message': "修改后的证书在系统中已经存在！"}
            }
            return JsonResponse(res)
        # 如果没有return,则保存前端提交的基本信息
        liscense.name = liscense_name
        liscense.level = liscense_level
        liscense.organ = liscense_organ
        liscense.start_date = start_date
        liscense.empire_date = empire_date

        # 处理上传文件的问题
        # liscense_path 为前端传送表单中的文件路径
        liscense_path = data.get('fullpath')

        if liscense_path:
            # 将urlencode之后的url解码（decode）
            liscense_path = unquote(liscense_path).replace('\\', '/')

            # 判断用户是否修改了证书文件，如果修改了，则liscense_path中包含‘liscensetemp’字符串，则按照新的路径保存证书文件
            if 'liscensetemp' not in liscense_path:
                pass
            else:
                liscense_path = liscense_path.split(API_HOST + '/')[-1]
                liscense_path = os.path.join(BASE_DIR, liscense_path)
                liscense_file = open(liscense_path, 'rb')
                # extension为文件后缀名
                extension = liscense_path.split('.')[-1]
                folder = os.path.join(BASE_DIR, 'media/liscenses/{0}({1})'.format(member.name, member.id_num))
                if not os.path.exists(folder):
                    os.makedirs(folder)
                filepath = os.path.join(folder, '{0}+{1}{2}+{3}.{4}'.format(member.name, liscense_name, liscense_level,
                                                                            liscense_organ, extension))
                with open(filepath, 'wb') as f:
                    for line in liscense_file.readlines():
                        f.write(line)
                    f.flush()
                liscense_file.flush()
                liscense_file.close()
                os.remove(liscense_path)
                shortpath = filepath.split(MEDIA_ROOT + '/')[-1]
                liscense.pdffile = shortpath
                liscense.is_confirmed = False
                liscense.confirm_user = None
        else:
            # 如果用户没有提交文件路径，则需要判断之前是否存在证书文件，如果存在，则进行删除
            if liscense.pdffile:
                os.remove(os.path.join(BASE_DIR, liscense.pdffile.path))
                liscense.pdffile = None
                liscense.is_confirmed = False
                liscense.confirm_user = None
        liscense.save()
        res = {
            'data': None,
            'meta': {'status': 200, 'message': '修改证书信息成功'}
        }
    else:
        res = {
            'data': None,
            'meta': {'status': 802, 'message': '请求方法不被允许'}
        }
    return JsonResponse(res)

# 证书列表导出到excel
def export_to_excel(request):
    query_info = request.GET
    members = member_filter(query_info)
    excel_url = member_to_excelpath(members)
    res = {
        'data': {'excel_url': excel_url},
        'meta': {'status': 200, 'message': "导出Excel成功！"}

    }
    return JsonResponse(res)

# liscense数据统计表格使用的统计数据
def liscense_tab(request):
    if request.method == 'GET':
        LiscenseNameStr = request.GET.get('LiscenseNameStr')
        LiscenseLevelStr = request.GET.get('LiscenseLevelStr')
        LiscenseOrganStr = request.GET.get('LiscenseOrganStr')
        CompanyStr = request.GET.get('CompanyStr')
        print(request.GET)
        con = Q()
        if LiscenseNameStr:
            liscenseNameList = LiscenseNameStr.split(',')
            q1 = Q(name__in=liscenseNameList)
            con.add(q1, 'AND')
        if LiscenseLevelStr:
            liscenseLevelList = LiscenseLevelStr.split(',')
            q2 = Q(level__in=liscenseLevelList)
            con.add(q2, 'AND')
        if LiscenseOrganStr:
            liscenseOrganList = LiscenseOrganStr.split(',')
            q3 = Q(organ__in=liscenseOrganList)
            con.add(q3, 'AND')
        if CompanyStr:
            CompanyList = CompanyStr.split(',')
            q4 = Q(member__company__in=CompanyList)
            q5 = Q(member__is_delete=False)
            con.add(q4, 'AND')
            con.add(q5, 'AND')
        q6 = Q(is_delete=False)
        con.add(q6, 'AND')
        liscenses = Liscense.objects.filter(con)
        res = {
            'data': None,
            'meta': {'status': 200, 'message': '获取liscense统计数据成功！'}
        }
        return JsonResponse(res)




